﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jumpton.SFA.Server.Entity;
using Jumpton.Persistent;
using Jumpton.Data;
using System.Data;

namespace Jumpton.SFA.Server.BusinessRule.MasterData
{
    public class CustomerManager : BusinessLogic
    {
        public ObjectTable GetCourseTable(decimal domainID)
        {
            return new ObjectTable(typeof(CUSTOMERS), "this.DOMAINID='" + domainID + "'");
        }

        public CUSTOMERS Load(decimal id)
        {
            return (CUSTOMERS)ObjectRow.Load(typeof(CUSTOMERS), string.Format("this.ID='{0}'", id));
        }

        public static ObjectTable GetCustomers(decimal domainid)
        {
            return new ObjectTable(typeof(CUSTOMERS), "this.DOMAINID='" + domainid + "'");
        }
        public static DataSet GetCustomersByDomainID(decimal domainid, int mid, string where)
        {
            DataSet ds = null;
            string sql = @"SELECT cast(id as nvarchar) as id,1 AS pId ,name,'true' as [open],
            case when isnull(MEASURE_PROFILE_ID,0)=0 then 'false' else (case when MEASURE_PROFILE_ID={0} then 'true' else 'false' end) end  as [checked],
case when isnull(MEASURE_PROFILE_ID,0)=0 then 'false' else (case when MEASURE_PROFILE_ID={1} then 'false' else 'true' end) end  as [message],
  '../css/zTreeStyle/img/user.png' as icon
FROM CUSTOMERS WHERE DOMAIN_ID={2}";
            sql = string.Format(sql, mid, mid, domainid);
            sql += where;
            ds = SqlData.OpenSql(sql);
            return ds;
        }
        public static ObjectTable GetCustomers(string where)
        {
            return new ObjectTable(typeof(CUSTOMERS), where);
        }
        public static DataSet SearchCustomer(string where)
        {
            return SqlData.OpenSql("select distinct C.ID,C.NAME,C.IDENTITY1,C.IDENTITY2 from CUSTOMERS C INNER JOIN order_headers  OH ON C.ID=OH.CUSTOMER_ID AND OH.STATUS=0 " + where);

        }
        public CUSTOMERS LoadWithDomainID(string CUSTOMERSCode, decimal DomainID, decimal ID)
        {
            return (CUSTOMERS)ObjectRow.Load(typeof(CUSTOMERS), string.Format("this.CODE='{0}' AND this.DOMAINID='{1}' AND this.ID<>'{2}'", CUSTOMERSCode, DomainID, ID));
        }

        public static DataSet SearchCustomer(string strCondition, string isFirst, string valid, int pageIndex, int pageSize, bool selectAll)
        {
            return SqlData.OpenSP("SP_Select_CUSTOMERS", strCondition, isFirst, valid, pageIndex, pageSize, selectAll ? "1" : "0");
        }

        public static DataSet SearchCustomer_excel(string strCondition, string isFirst, string valid, int pageIndex, int pageSize, bool selectAll)
        {
            return SqlData.OpenSP("usp_SelectCUSTOMERS", strCondition, isFirst, valid, pageIndex, pageSize, selectAll ? "1" : "0");
        }

        /// <summary>
        /// 查找客户
        /// </summary>
        /// <param name="domainid">所在的域</param>
        /// <param name="Lat"></param>
        /// <param name="Lon"></param>
        /// <param name="CustomerType"></param>
        /// <param name="MemberLevel"></param>
        /// <returns></returns>
        public static ObjectTable SearchCustomer(decimal domainid, decimal Lat, decimal Lon, string CustomerType, string MemberLevel)
        {
            return new ObjectTable(typeof(CUSTOMERS), string.Format(@"this.DOMAINID='{0}' and (Identity1 between {1} and {2} ) 
                and (Identity2 between {3} and {4}) {5} {6} ", domainid, Lat - 1, Lat + 1, Lon - 1, Lon + 1, string.IsNullOrEmpty(CustomerType) ? "" : " and Local_Level1_Code='" + CustomerType + "'", string.IsNullOrEmpty(CustomerType) ? "" : " and bracket_id='" + MemberLevel + "'"));
        }

        public static DataSet SearchCustomerIncludeChain(decimal chainID, string strCondition)
        {
            return SqlData.OpenSP("[usp_SelectCUSTOMERSsDynamicForChianCustomer]", chainID, strCondition);
        }

        public static void DisableCustomerRoute(decimal customerID)
        {
            string sql = " DELETE ROUTE_CUSTOMERS WHERE  CUSTOMER_ID=" + customerID.ToString();
            SqlData.ExecuteSql(sql);
        }

        public static void UpdateRouteCustomerForInvalidCustomer(int customerID)
        {
            string SQL = string.Format(@"UPDATE ROUTE_CUSTOMERS SET VALID = 0 WHERE CUSTOMER_ID = {0}", customerID);

            SqlData.ExecuteSql(SQL);
        }
        /// <summary>
        /// 获取该家门店共有多少张门店形象照片
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public int GetStorePhotoCount(decimal customerId)
        {
            int count = 0;
            try
            {
                string SQL = string.Format("select count(*) from CUSTOMER_STORE_PHOTO WHERE customer_id = {0}", customerId);

                count = (int)SqlData.OpenSql(SQL).Tables[0].Rows[0][0];
            }
            catch { }
            return count;
        }

        public static DataSet SearchCustomerForProductList(int productListID, string strCondition, string isSelected)
        {
            return SqlData.OpenSP("usp_SelectCustomersForProductList", productListID, strCondition, isSelected);
        }

        public static DataSet SearchCustomerForIcoProfile(int iocProfileID, string strCondition, string isSelected)
        {
            return SqlData.OpenSP("usp_SelectCustomersForIntertoryTarget", iocProfileID, strCondition, isSelected);
        }

        public static void AssignCustomerForProductList(bool checkFlag, decimal customerID, int productListID)
        {
            SqlData.ExecuteSP("sp_AssignCustomerForProductList", checkFlag, customerID, productListID);
        }

        public static void AssignCustomerForIcoProfile(bool checkFlag, int customerID, int iocProfileID)
        {
            SqlData.ExecuteSP("sp_AssignCustomerForIcoProfile", checkFlag, customerID, iocProfileID);
        }

        public void UpdateCustomerCode(decimal customerID)
        {
            SqlData.ExecuteSP("sp_SetCustomerCode", customerID.ToString());
        }
        /// <summary>
        /// 暂用于，地图模式数据查询
        /// </summary>
        /// <param name="domainId"></param>
        /// <param name="strWhere"></param>
        public DataTable GetCustomerInfoByWhere(decimal domainId, string strWhere)
        {

            string sql = string.Format(@"select c.*,
                                        ci.ADDRESS_LINE,ci.SLOG_CODE,ci.TELEPHONE,ci.FAX
                                        from CUSTOMERS c left join CONTACT_INFO ci on c.ID=ci.CUSTOMER_ID
                                        where c.domain_id={0} {1}", domainId, strWhere);
            return SqlData.OpenSql(sql).Tables[0];
        }

        public decimal Save(CUSTOMERS customer)
        {
            if (customer != null)
            {
                try
                {
                    if (customer.State == DataRowState.Added)
                    {
                        // customer.CODE = "0";
                        // customer.NAME2 = Guid.NewGuid().ToString();

                    }
                    customer.Save();

                    //新增客戶后更新編號
                    if (customer.State == DataRowState.Added)
                        UpdateCustomerCode(customer.ID);

                    return customer.ID;
                }
                catch (Exception err)
                {
                    message = err.Message; throw err;
                }
            }
            return 0;
        }

        public bool Delete(CUSTOMERS customer)
        {
            bool Successful = false;
            if (customer != null)
            {
                try
                {
                    customer.Delete();
                    Successful = true;
                }
                catch (Exception err)
                {
                    message = err.Message; throw err;

                }
            }

            return Successful;
        }
    }
}
